package SwordFingerOffer;

public class Q53_NumCountInArray {

    static int count = 0;

    //统计一个数字在排序数组中出现的次数
    //二分走起
    public int search(int[] nums, int target) {
        int left = 0;
        int right = nums.length - 1;
        int mid = 0;
        while (left <= right){
            mid = (right + left) / 2; //防溢出
            if (nums[mid] == target){
                count++;
                //两边检索
                int i = mid;
                while (i + 1 != nums.length && nums[i + 1] == target) {
                    count ++;
                    i++;
                }
                i = mid;
                while (i - 1 != -1 && nums[i - 1] == target) {
                    count ++;
                    i--;
                }
                break;
            }else if (nums[mid] < target){
                left = mid + 1;
            }else {
                right = mid - 1;
            }
        }
        return count;
    }

    public static void main(String[] args) {
        Q53_NumCountInArray fun = new Q53_NumCountInArray();
        int[] arr = new int[]{5,7,7,8,8,10};
        System.out.println(fun.search(arr, 10));
    }

}
